package com.verlet.springbootdemo.simple.disruptor.netty.client;

import com.lmax.disruptor.BlockingWaitStrategy;
import com.lmax.disruptor.dsl.ProducerType;
import com.verlet.springbootdemo.simple.disruptor.netty.AbstractMessageConsumer;
import com.verlet.springbootdemo.simple.disruptor.netty.MarshallingCodeFactory;
import com.verlet.springbootdemo.simple.disruptor.netty.RingBufferWorkPoolFactory;
import com.verlet.springbootdemo.simple.disruptor.netty.TranslatorData;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author verlet
 * @date 2020/8/17
 */
@Slf4j
public class NettyClient {

    public static final String HOST = "127.0.0.1";
    public static final int PORT = 8765;

    private Channel channel;

    public NettyClient() {

        NioEventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(workerGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline()
                                    .addLast(MarshallingCodeFactory.buildMarshallingDecoder())
                                    .addLast(MarshallingCodeFactory.buildMarshallingEncoder())
                                    .addLast(new ClientHandler());
                        }
                    });

            ChannelFuture channelFuture = bootstrap.connect(HOST, PORT).sync();
            log.info("Client端连接中。。");
            this.channel = channelFuture.channel();

            sendMessage();
            channelFuture.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();

        }
    }

    public void sendMessage() {
        for (int i = 0; i < 10; i++) {
            TranslatorData translatorData = new TranslatorData();
            translatorData.setId(String.valueOf(i));
            translatorData.setName("Name" + i);
            translatorData.setMessage("这是第" + i + "条消息");

            this.channel.write(translatorData);
        }
        this.channel.flush();
    }

    public static void main(String[] args) {

        AbstractMessageConsumer[] messageConsumers = new AbstractMessageConsumer[8];
        for (int i = 0; i < messageConsumers.length; i++) {
            com.verlet.springbootdemo.simple.disruptor.netty.client.MessageConsumerImpl messageConsumer =
                    new com.verlet.springbootdemo.simple.disruptor.netty.client.MessageConsumerImpl("code:serverId:client:" + i);
            messageConsumers[i] = messageConsumer;
        }

        RingBufferWorkPoolFactory.getInstance().initAndStart(ProducerType.MULTI, 1024*1024,new BlockingWaitStrategy(),messageConsumers);

        new NettyClient();
    }

}
